package com.peng.leetcode.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * SumNumbers
 * <p>
 * 129. 求根到叶子节点数字之和
 *
 * @author: lupeng6
 * @create: 2021/1/28 17:26
 */
public class SumNumbers {

    public static void main(String[] args) {
        TreeNode treeNode = TreeMain.array2tree(new Integer[]{1, 2, 3});
        System.out.println(new SumNumbers().sumNumbers(treeNode));
    }

    private List<String> result = new ArrayList<>();

    public int sumNumbers(TreeNode root) {
        int sum = 0;
        preOrder(root, "");
        for (String s : result) {
            sum += Integer.valueOf(s);
        }
        return sum;
    }

    private void preOrder(TreeNode node, String str) {
        if (node.left == null && node.right == null) {
            result.add(str + node.val);
        } else {
            if (node.left != null) {
                preOrder(node.left, str + node.val);
            }
            if (node.right != null) {
                preOrder(node.right, str + node.val);
            }
        }
    }
}
